import { useCallback, useEffect } from "react";
import { loadSearchs, saveSearchs } from "storage";
import { useState } from "react";

// 搜索记录的hooks
export const useSearchs = () => {
  const [searchs, setSearchs] = useState<string[]>(loadSearchs());

  // 查询搜索记录
  const listSearchs = useCallback(() => {
    setSearchs(loadSearchs());
  }, []);

  useEffect(() => {
    listSearchs();
  }, [listSearchs]);

  // 增加搜索记录
  const createSearch = useCallback(
    (content: string) => {
      let newSearchs = [...searchs];
      if (newSearchs.includes(content.trim())) {
        newSearchs.splice(newSearchs.indexOf(content.trim()), 1);
      }
      newSearchs = [content.trim(), ...newSearchs];
      if (newSearchs.length > 10) {
        newSearchs = newSearchs.slice(0, 10)
      }
      setSearchs(newSearchs);
      saveSearchs(newSearchs);
    },
    [searchs, setSearchs]
  );

  // 删除某个搜索记录: 这个功能暂时没用上, 后期可能要用到, 先实现了, 测试过了没问题
  const removeSearch = useCallback(
    (content: string) => {
      console.log(content);
      const newSearchs = [...searchs];
      if (newSearchs.includes(content)) {
        newSearchs.splice(newSearchs.indexOf(content), 1);
      }
      console.log(newSearchs);
      setSearchs(newSearchs);
      saveSearchs(newSearchs);
    },
    [searchs, setSearchs]
  );

  // 清空所有搜索记录
  const clearSearchs = useCallback(() => {
    setSearchs([]);
    saveSearchs([]);
  }, [setSearchs]);

  return {
    searchs,
    createSearch,
    removeSearch,
    clearSearchs,
  };
};
